package com.alex.monitor.core.alarm.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alex.monitor.core.properties.AlexMonitorProperties;
import com.alex.monitor.core.properties.AlexMonitorProperties.HttpConfig;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

/**
 * 基于HTTP的报警器，用于通过HTTP发送监控信息
 *
 * @author Alex.Liu
 * @date: 2025-02-16 15:38
 * @since 1.0.0
 */
@Slf4j
public class DefaultHttpMonitorAlarm extends AbstractMonitorAlarm {


    /**
     * HTTP配置信息
     */
    private final HttpConfig config;


    public DefaultHttpMonitorAlarm(AlexMonitorProperties properties) {
        super(properties);
        this.config = properties.getHttp();
    }

    @Override
    protected void doAlarm(String tag, JSONObject message) {
        HttpRequest request = HttpUtil.createRequest(config.getMethod(), config.getUrl());
        request.addHeaders(config.getHeaders());
        request.contentType(config.getContentType());
        request.charset(config.getDefaultEncoding());
        request.body(message.toJSONString());
        try (HttpResponse response = request.execute()) {
            if (!response.isOk()) {
                log.error("alarm error url:{} status={}", config.getUrl(), response.getStatus());
            }
        } catch (Exception e) {
            log.error("alarm error url:{}", config.getUrl(), e);
        }
    }

}